package com.three.crm.alioos;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;

import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.callback.OSSProgressCallback;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSStsTokenCredentialProvider;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.three.crm.util.LogUtils;
import com.three.crm.util.ToastUtils;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Calendar;

public class AliyunOSSUploadHelper {

    private Context context;
    private String bucketName;
    private String endpoint;
    private String accessKeyId;
    private String accessKeySecret;
    private String securityToken;

    public AliyunOSSUploadHelper(Context context, String bucketName, String endpoint, String accessKeyId, String accessKeySecret, String securityToken) {
        this.context = context;
        this.bucketName = bucketName;
        this.endpoint = endpoint;
        this.accessKeyId = accessKeyId;
        this.accessKeySecret = accessKeySecret;
        this.securityToken = securityToken;
    }

    private OSSClient getOSSClient() {
        OSSCredentialProvider credentialProvider = new OSSStsTokenCredentialProvider(accessKeyId, accessKeySecret, securityToken);
        return new OSSClient(context, endpoint, credentialProvider);
    }

    public void uploadFile(final String filePath,String fileType,String fileName, final OSSCallback callBack) {
        OSSClient oss = getOSSClient();
        if (oss == null) {
            ToastUtils.showToast("初始化失败");
            return;
        }
        File file = new File(filePath);
        String cosPath = getCosFile(fileType);
        if(TextUtils.isEmpty(fileName)){
            cosPath += file.getName();
        } else {
            cosPath += fileName;
        }

        String finalCosPath = cosPath;
        PutObjectRequest put = new PutObjectRequest(bucketName, finalCosPath, filePath);
        // 设置该请求是否支持断点续传，参数为true则支持断点续传，默认为true
        try {
            //获取可访问的url
            String url = "http://shuangyong.ifkdx.com/" + finalCosPath;
                    //oss.presignPublicObjectURL(bucketName, finalCosPath);

            put.setProgressCallback(new OSSProgressCallback<PutObjectRequest>() {
                @Override
                public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {
                    callBack.onProgress(currentSize,totalSize,"");
                }
            });
            oss.asyncPutObject(put, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
                @Override
                public void onSuccess(PutObjectRequest request, PutObjectResult result) {
                    callBack.onSuccess(url);
                }

                @Override
                public void onFailure(PutObjectRequest request, ClientException clientException, ServiceException serviceException) {
                    Log.i("TAG", "onFailure");
                    if (clientException != null) {
                    // 本地异常，如网络异常等。
                        clientException.printStackTrace();
                    }
                     if (serviceException != null) {
                        // 服务异常。
                        Log.e("ErrorCode", serviceException.getErrorCode());
                        Log.e("RequestId", serviceException.getRequestId());
                        Log.e("HostId", serviceException.getHostId());
                        Log.e("RawMessage", serviceException.getRawMessage());
                    }
                    callBack.onFailure(clientException, serviceException);
                    LogUtils.onUploadLog("文件上传失败：" + clientException.getMessage() + serviceException.getMessage());
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static String getCosFile(String type){
        String res = "";
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        Calendar calendar = Calendar.getInstance();
        int minute = calendar.get(Calendar.MINUTE);
        int second = calendar.get(Calendar.SECOND);
        if (type.contains("video")) {
            res = "video/";
        } else {
            res = "cover/";
        }
        return "guatu/" + res + dateFormat.format(calendar.getTime()) + "/" + minute + second + "_";
    }

    public interface OSSCallback {
        void onProgress(long complete, long target,String url);
        void onSuccess(String url);
        void onFailure(ClientException clientExcepion, ServiceException serviceException);
    }
}
